﻿using System.Diagnostics;
using System.IO;
using UnityEditor;
using Debug = UnityEngine.Debug;

namespace XUSVN
{
    namespace Editor
    {
        public class XUSVNMenus
        {
            [MenuItem("Assets/XUSVN/Update", false, 4)]
            public static void Update()
            {
                string path = AssetDatabase.GetAssetPath(Selection.activeInstanceID);
                if (Directory.Exists(path) || File.Exists(path))
                {
                    RunCMD(@"TortoiseProc.exe /command:update /path:" + path + " /closeonend:0");
                }
                else
                {
                    Debug.LogError("路径不存在: " + path);
                }
            }

            [MenuItem("Assets/XUSVN/Commit", false, 4)]
            public static void Commit()
            {
                string path = AssetDatabase.GetAssetPath(Selection.activeInstanceID);
                if (Directory.Exists(path) || File.Exists(path))
                {
                    RunCMD(@"TortoiseProc.exe /command:commit /path:" + path + " /closeonend:0");
                }
                else
                {
                    Debug.LogError("路径不存在: " + path);
                }
            }

            public static string RunCMD(string strInput)
            {
                Process p = new Process();
                //设置要启动的应用程序
                p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                //是否使用操作系统shell启动
                p.StartInfo.UseShellExecute = false;
                // 接受来自调用程序的输入信息p
                p.StartInfo.RedirectStandardInput = true;
                //输出信息
                p.StartInfo.RedirectStandardOutput = true;
                // 输出错误
                p.StartInfo.RedirectStandardError = true;
                //不显示程序窗口
                p.StartInfo.CreateNoWindow = true;
                //启动程序
                p.Start();

                //向cmd窗口发送输入信息
                p.StandardInput.WriteLine(strInput + "&exit");

                p.StandardInput.AutoFlush = true;

                //获取输出信息
                string strOuput = p.StandardOutput.ReadToEnd();
                //等待程序执行完退出进程
                p.WaitForExit();
                p.Close();

                return strOuput;
            }
        }
    }
}
